<?php


namespace app\api\helpers\v1\traits;


use app\api\model\v1\SystemConfig;
use PhpOffice\PhpSpreadsheet\IOFactory;

trait FileUpload
{
    /**
     * @param $file //文件
     * @param $folder //文件夹名称
     * 上传图片
     * @return array
     */
    public function save($file, $folder)
    {
        $saveName = \think\facade\Filesystem::disk('public')
            ->putFile($folder, $file);
        $path = str_replace('\\', '/', $saveName);
        return [
            'path' => $path,
        ];
    }

    /**
     * @param $file
     * @param $folder
     * @param $fileName
     * @User: 刘海龙
     * @Date: 2021/8/30
     * @Time: 8:29
     * @return array
     * 指定文件名称
     */
    public function saveFileAs($file, $folder,$fileName){
        $saveName = \think\facade\Filesystem::disk('public')
            ->putFileAs($folder, $file,$fileName);
        $path = str_replace('\\', '/', $saveName);
        return [
            'path' => $path,
        ];
    }

    //创建文件夹
    public function mkdirs($dir, $mode = 0777)
    {
        if (is_dir($dir) || @mkdir($dir, $mode)) {
            return true;
        }
        if (!mkdir(dirname($dir), $mode)) {
            return false;
        }
        return @mkdir($dir, $mode);
    }


    /**
     * @param $file
     * @param $folder
     * @param string $type multistage  多级    stage 单级 直接导入
     * @User: 刘海龙
     * @Date: 2021/8/25
     * @Time: 18:18
     * @return array
     */
    public function saveImportExcel($file, $folder,$type='multistage')
    {
        $saveName = \think\facade\Filesystem::disk('public')->putFile($folder, $file);
        $path = app()->getRootPath() . 'public/storage/' . str_replace('\\', '/', $saveName);
        if ($type==='stage'){
            $data = $this->loadExcel($path);
        }else{
            $returnData = $this->loadExcel($path);
            $data = $this->dadaFilter($returnData);
        }
        return $data;
    }


    //载入excel
    public function loadExcel($filePath)
    {
        $inputFileType = IOFactory::identify($filePath);
        $reader = IOFactory::createReader($inputFileType);
        $reader->setReadDataOnly(TRUE);
        $spreadsheet = $reader->load($filePath); //载入excel表格
        $res_arr = array();
        $reader = $spreadsheet->getWorksheetIterator();
        foreach ($reader as $sheet) {
            //读取表内容
            $content = $sheet->getRowIterator();
            //逐行处理
            foreach ($content as $key => $items) {
                $rows = $items->getRowIndex();              //行
                $columns = $items->getCellIterator();       //列
                $row_arr = array();
                //确定从哪一行开始读取
                if ($rows < 2) {
                    continue;
                }
                //逐列读取
                foreach ($columns as $head => $cell) {

                    $data = $cell->getValue();

                    $row_arr[] = $data;
                }

                array_push($res_arr, array_values(array_filter($row_arr, function ($var) {
                    return $var !== null;
                })));

            }
        }
        return $res_arr;
    }


    //处理excel (多级)
    public function dadaFilter(array $array)
    {
        $filterData = [];
        $k1 = $i1 = $j1 = $k2 = $i2 = $i3 = $i4 = 0;
        if (count(reset($array)) == 7) {
            foreach ($array as $data) {
                if (count($data) == 7) {
                    $i1 = $j1 = 0;
                    $filterData[$k1] = ['years_title' => $data[0]];
                    $filterData[$k1]['item'][$i1] = [
                        'month_title' => $data[1],
                    ];
                    $filterData[$k1]['item'][$i1]['item'][] = [
                        'online_date' => gmdate('Y-m-d', (intval($data[2]) - 25569) * 24 * 60 * 60),
                        'detail_title' => $data[3],
                        'online_week' => $data[4],
                        'remark' => $data[5],
                        'online_status' => $data[6],
                    ];
                    $k2 = $k1;
                    $i2 = $i1;
                    $i4 = $i3 = $j1;
                    $k1++;
                    $i1++;
                    $j1++;
                }

                if (count($data) == 6) {
                    $filterData[$k2]['item'][$i1] = [
                        'month_title' => $data[0],
                    ];
                    $filterData[$k2]['item'][$i1]['item'][] = [
                        'online_date' => gmdate('Y-m-d', (intval($data[1]) - 25569) * 24 * 60 * 60),
                        'detail_title' => $data[2],
                        'online_week' => $data[3],
                        'remark' => $data[4],
                        'online_status' => $data[5],
                    ];
                    $i2 = $i1;
                    $i4++;
                    $i1++;
                }
                if (count($data) == 5) {
                    $filterData[$k2]['item'][$i2]['item'][] = [
                        'online_date' => gmdate('Y-m-d', (intval($data[0]) - 25569) * 24 * 60 * 60) ?? '空',
                        'detail_title' => $data[1],
                        'online_week' => $data[2],
                        'remark' => $data[3],
                        'online_status' => $data[4],
                    ];
                    $i3++;
                    $j1++;
                }
                if (count($data) == 4) {
                    $filterData[$k2]['item'][$i2]['item'][] = [
                        'online_date' => gmdate('Y-m-d', (intval($data[0]) - 25569) * 24 * 60 * 60),
                        'detail_title' => $data[1],
                        'online_week' => $data[2],
                        'remark' => '',
                        'online_status' => $data[3],
                    ];
                    $i3++;
                    $j1++;
                }
            }
        }
        return array_values($filterData);
    }

    /**
     * @param $str
     * @User: 刘海龙
     * @Date: 2021/9/2
     * @Time: 11:59
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 过滤敏感字符
     */
    public function filterSensitive($str){
        $config = SystemConfig::where(['name' => 'sensitive'])->find();
        if (!is_null($config)) {
            //获取敏感字符的字符串并且转换为数组
            $sensitive_string = $config['value'];
            $sensitive_arr = explode(',',$sensitive_string);
            $word = array_combine($sensitive_arr, array_fill(0, count($sensitive_arr), '****'));
            $filter_str = strtr($str, $word);
        }else{
            $filter_str = $str;
        }
        return $filter_str;
    }


    /**
     * @param $file_path
     * @User: 刘海龙
     * @Date: 2021/9/13
     * @Time: 16:48
     * 下载excel 模板
     */
    public function downloadExcel($file_path){
        header("Content-type:text/html;charset=utf-8");
        if(!file_exists($file_path)){
            echo "没有该文件文件";
            return ;
        }
        $fp=fopen($file_path,"r");
        $file_size=filesize($file_path);
        //下载文件需要用到的头
        Header("Content-type: application/octet-stream");
        Header("Accept-Ranges: bytes");
        Header("Accept-Length:".$file_size);
        Header("Content-Disposition: attachment; filename=".$file_path);
        $buffer=1024;
        $file_count=0;
        //向浏览器返回数据
        while(!feof($fp) && $file_count<$file_size){
            $file_con=fread($fp,$buffer);
            $file_count+=$buffer;
            echo $file_con;
        }
        fclose($fp);

    }


}
